const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')

const files = require('./routes/files')
const users = require('./routes/users')
const { initUsers } = require('./models/users')
const verifyToken = require('./middleware/auth')

// 初始化用户数据
initUsers().catch(err => {
    console.error('初始化用户数据失败:', err)
})

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
    extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
    const start = new Date()
    await next()
    const ms = new Date() - start
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
// 为 files 路由添加 token 验证中间件
app.use(async (ctx, next) => {
    // 如果是 files 相关的路由，需要验证 token
    if (ctx.path.startsWith('/files')) {
        await verifyToken(ctx, next);
    } else {
        await next();
    }
});

// 注册路由
app.use(files.routes(), files.allowedMethods())
app.use(users.routes(), users.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app